#!/usr/bin/env python

"""
@file tools/Classes.python/class.DataController.py

@date 29-dec-2012

@author Youri Hoogstrate

@version 1.3.6

@section LICENSE
yh-kt-fold can predict RNA 2D structures including K-turns.
Copyright (C) 2012-2013 Youri Hoogstrate

This file is part of yh-kt-fold.

yh-kt-fold is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

yh-kt-fold is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""

#import urllib2
from xml.dom.minidom import parseString

class DataController:
	motifs = {}
	rnas = []
	
	def __init__(self,xmlfile):
		self.xmlfile = xmlfile
		
		self.read()
	
	def read(self):
		fh = open(self.xmlfile,'r')
		data = fh.read()
		fh.close()
		
		dom = parseString(data)
		
		for motif in dom.getElementsByTagName('motif'):					# Read motifs
			mtif_xml = motif.toxml()
			
			name        = motif.getElementsByTagName('id')[0].firstChild.data
			p5_sequence = motif.getElementsByTagName('p5')[0].firstChild.data
			p3_sequence = motif.getElementsByTagName('p3')[0].firstChild.data
			bonds       = motif.getElementsByTagName('bonds')[0].firstChild.data
			energy      = motif.getElementsByTagName('energy')[0].firstChild.data
			
			self.motifs[name] = {'5':p5_sequence,'3':p3_sequence,'x':bonds,'e':energy}
		
		for rna in dom.getElementsByTagName('rna'):						# Read RNAs
			name        = rna.getElementsByTagName('title')[0].firstChild.data
			
			_organism   = rna.getElementsByTagName('organism')
			if(len(_organism) > 0):
				organism = _organism[0].firstChild.data
			else:
				organism = 'unknown/universal'
			
			sequence    = rna.getElementsByTagName('sequence')[0].firstChild.data
			structure   = rna.getElementsByTagName('structure')[0].firstChild.data
			kturn       = rna.getElementsByTagName('link')[0].firstChild.data
			prediction  = rna.getElementsByTagName('predictions')[0]
			
			predictions = []
			
			for predicted_sequence in prediction.getElementsByTagName('structure'):
				_structure   = predicted_sequence.firstChild.data
				_motif_count = predicted_sequence.getAttribute('motifs')
				predictions.append({'structure':_structure,'motif-count':_motif_count})
			
			self.rnas.append('a')
			self.rnas.append({'name':name,'organism':organism,'sequence':sequence,'structure':structure,'k-turn':kturn,'predictions':predictions})
		
		return True
